﻿using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc.Controllers;
using Swashbuckle.AspNetCore.Swagger;
using Swashbuckle.AspNetCore.SwaggerGen;
using SXICE.WebAPI.Models;
using System.Collections.Generic;
using System.Linq;

namespace SXICE.WebAPI.Filters
{
    /// <summary>
    /// 添加验证Token头部参数过滤器
    /// </summary>
    public class AddAuthTokenHeaderParameter : IOperationFilter
    {
        private readonly JwtSettings jwtSettings;

        public AddAuthTokenHeaderParameter(JwtSettings jwtSettings)
        {
            this.jwtSettings = jwtSettings;
        }

        public void Apply(Operation operation, OperationFilterContext context)
        {
            if (this.jwtSettings.AuthorizationType == AuthorizationTypeEnum.Cookie)
                return;
            if (operation.Parameters == null)
                operation.Parameters = new List<IParameter>();
            var attrs = context.ApiDescription.ActionDescriptor.AttributeRouteInfo;
            //先判断是否是匿名访问,
            var descriptor = context.ApiDescription.ActionDescriptor as ControllerActionDescriptor;
            if (descriptor != null)
            {
                var actionAttributes = descriptor.MethodInfo.GetCustomAttributes(true);
                bool isAnonymous = actionAttributes.Any(a => a is AllowAnonymousAttribute);
                //非匿名的方法,链接中添加accesstoken值
                if (!isAnonymous)
                {
                    operation.Parameters.Add(new NonBodyParameter()
                    {
                        Description = "请求的Token，登录成功之后会返回一个Token，把这个Token放在头部的Authorization中",
                        Name = "Authorization",
                        In = "header",
                        Type = "string",
                        Required = false //是否必选
                    });
                }
            }
        }
    }
}
